<?php

class ActionAdd extends BaseAction
{
    public function run()
    {
        $iUserId = Yii::app()->user->id;
    	$aCurrencies = Lot::getCurrencies();
        $aPlacementTimesNames = Lot::getPlacementTimesNames();
        $aTariffPlans = TariffPlan::model()->getAvailableTariffPlans($iUserId);

        if(count($aTariffPlans) == 0)
        {
            Yii::app()->user->setFlash('my_lots_manage', 'У вас нет доступных тарифных планов');
            Yii::app()->controller->redirect(Yii::app()->controller->createUrl('/profile/my_lots'));
        }

        $oLot = new Lot();

        if ( Yii::app()->request->getIsPostRequest() )
        {
            $oLot->setAttributesFromRequest('aLot');
            $aSelectedTariff = array();

            $oLot->user_id = $iUserId;
            $oLot->date_created = date('Y-m-d H:i:s');

            $aPlacementTimes = Lot::getPlacementTimes();
            $aTariffPlansExpirationDates = array();

            foreach ($aTariffPlans as $aTariffPlan)
            {
                $aTariffPlansExpirationDates[$aTariffPlan['tariff_plan_id']] = strtotime($aTariffPlan['date_expired']);
                if ($aTariffPlan['tariff_plan_id'] == $oLot->tariff_plan_id)
                {
                    $aSelectedTariff = $aTariffPlan;
                }
            }

            if($aSelectedTariff['tariff_plan'] == TariffPlan::PLAN_SELLER)
            {
                $oLot->type = 'sale';
            }

            $iDateExpired = strtotime($aPlacementTimes[$oLot->placement_time]);

            $oLot->date_expired = ($iDateExpired > $aTariffPlansExpirationDates[$oLot->tariff_plan_id])?date('Y-m-d H:i:s', $aTariffPlansExpirationDates[$oLot->tariff_plan_id]):date('Y-m-d H:i:s', $iDateExpired);
            $oLot->status = 'active';

            if ($oLot->save())
            {
                $oLot->lot_number = $oLot->lot_id + 1000;

                if($oLot->update())
                {
                    $oTariffPlan = TariffPlan::model()->findByPk($oLot->tariff_plan_id);
                    $oTariffPlan->lots_left = $oTariffPlan->lots_left - 1;

                    if ($oTariffPlan->update())
                    {
                        Yii::app()->user->setFlash('my_lots_manage', 'Заявка под номером #'.$oLot->lot_number.' добавлена.');
                        Yii::app()->controller->redirect(Yii::app()->controller->createUrl('/profile/my_lots'));
                    }
                }
            }  
        }

    	$this->template->aCurrencies = $aCurrencies;
        $this->template->aPlacementTimesNames = $aPlacementTimesNames;
        $this->template->aTariffPlans = $aTariffPlans;
        $this->template->oLot = $oLot;
    }
}